package com.fjx.ai.controller;

import com.fjx.ai.service.AiChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AiController {

    private final ChatClient chatClient;

    private final AiChatHistoryService aiChatHistoryService;


    @PostMapping(value = "chat", produces = "text/html;charset=utf-8")
    public Flux<String> getAiResponse(@RequestParam("prompt") String question,
                                      @RequestParam("chatId") String chatId) {
        //先在内存中保存会话id
        aiChatHistoryService.saveConversationId("chat",chatId);
        //流式调用
        return chatClient
                .prompt()
                .user(question)
                .messages()
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))//springai定义的上下文信息，这里传递的是sdk定义的会话id枚举和对应的id
                .stream()
                .content();
    }
}
